
import time
from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler
from flask_apscheduler import APScheduler

from database2 import db_exec_one
from public import dingtalk

scheduler = APScheduler(scheduler=BackgroundScheduler(timezone='Asia/Shanghai'))


# 测试scheduler是否有效
# @scheduler.task('interval', id='do_job_1', seconds=10, misfire_grace_time=900)
# def job_example():
#     print('Job 1 executed')


# @scheduler.task('cron', id='weekly_report', week='*', day_of_week='fri', hour='12', minute='0', second='0')
# def job_cluster_weekly():
#     from blues.mon.mon_weekly_report import generate_weekly_cluster
#     localtime = time.asctime(time.localtime(time.time()))
#     print("------------> Time:", localtime, "开始执行prometheus周报计划任务")
#     generate_weekly_cluster()
#
#
# @scheduler.task('cron', id='weekly_report_skw', week='*', day_of_week='fri', hour='12', minute='10', second='0')
# def job_skw_weekly():
#     from blues.mon.mon_weekly_report import generate_weekly_skw
#     localtime = time.asctime(time.localtime(time.time()))
#     print("------------> Time:", localtime, "开始执行Skywalking周报计划任务")
#     generate_weekly_skw()


@scheduler.task('cron', id='daily_cloud_info', week='*', day_of_week='*', hour='1', minute='0', second='0')
def job_get_cloud_info():
    from blues.cloud.ascm import sync_depart, sync_depart_accounts
    from blues.cloud.ecs import record_ecs, record_disk
    from blues.cloud.rds import record_rds
    from blues.cloud.oss import record_oss
    from blues.cloud.slb import record_slb
    from blues.cloud.dds import record_dds
    from blues.cloud.vpc import record_eip
    from blues.cloud.cs import record_cs
    from blues.cloud.odps import record_odps
    success = "true"
    message = ""
    try:
        localtime = time.asctime(time.localtime(time.time()))
        print("------------> Time:", localtime, "开始执行计划任务: 每日获取Cloud云资源信息")
        if not sync_depart():
            raise Exception("sync_depart 出错")
        if not sync_depart_accounts():
            raise Exception("sync_depart_accounts 出错")
        if not record_ecs():
            raise Exception("record_ecs 出错")
        if not record_disk():
            raise Exception("record_disk 出错")
        if not record_rds():
            raise Exception("record_rds 出错")
        if not record_oss():
            raise Exception("record_oss 出错")
        if not record_slb():
            raise Exception("record_slb 出错")
        if not record_dds():
            raise Exception("record_dds 出错")
        if not record_eip():
            raise Exception("record_eip 出错")
        if not record_cs():
            raise Exception("record_cs 出错")
        if not record_odps():
            raise Exception("record_odps 出错")
        localtime = time.asctime(time.localtime(time.time()))
        print("------------> Time:", localtime, "计划任务结束: 每日获取Cloud云资源信息")
    except Exception as e:
        print(e)
        success = "false"
        message = str(e)
        dingtalk.job_succeed_msg("计划任务执行失败：" + message)
    finally:
        job_name = "daily_cloud_info"
        now = datetime.now()
        sql = "INSERT INTO apscheduler_job_results(job_name,success,message,`time`) VALUES('{}','{}','{}','{}')".format(
            job_name, success, message, now
        )
        db_exec_one(sql)


@scheduler.task('cron', id='daily_cms_info', week='*', day_of_week='*', hour='2', minute='0', second='0')
def job_get_cloud_cms_data():
    from blues.cloud.cms_ecs import record_cms_ecs
    from blues.cloud.cms_ecs_disk import record_cms_ecs_disk
    from blues.cloud.cms_rds import record_cms_rds
    from blues.cloud.cms_oss import record_cms_oss
    from blues.cloud.cms_mongo import record_cms_mongo
    from blues.cloud.cms_eip import record_cms_eip
    success = "true"
    message = "任务执行成功"
    s = time.time()
    try:
        s1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print("------------> Time:", s1, "开始执行计划任务: 每日获取CMS监控数据")
        # 执行开始
        if not record_cms_ecs():
            raise Exception("record_cms_ecs 出错")
        if not record_cms_ecs_disk():
            raise Exception("record_cms_ecs_disk 出错")
        if not record_cms_rds():
            raise Exception("record_cms_rds 出错")
        if not record_cms_oss():
            raise Exception("record_cms_oss 出错")
        if not record_cms_mongo():
            raise Exception("record_cms_mongo 出错")
        if not record_cms_eip():
            raise Exception("record_cms_eip 出错")

        # 执行完成
        s2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print("------------> Time:", s2, "计划任务结束: 每日获取CMS监控数据")
    except Exception as e:
        print(e)
        success = "false"
        message = str(e)
        dingtalk.job_succeed_msg("每日获取CMS数据任务执行失败：" + message)
    finally:
        job_name = "daily_cms_info"
        now = datetime.now()
        sql = "INSERT INTO apscheduler_job_results(job_name,success,message,`time`) VALUES('{}','{}','{}','{}')".format(
            job_name, success, message, now
        )
        db_exec_one(sql)
        s3 = time.time()
        print("------------> 任务耗时：", s3 - s)
